<template>
  <a-modal
    :title="title"
    :width="1400"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :okButtonProps="{ disabled: disableSubmit }"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    style="top: 20px"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <!-- 步骤条 -->
        <a-steps :current="currentStep" style="margin-bottom: 20px">
          <a-step title="选择入库类型" />
          <a-step title="物料信息" />
          <a-step title="入库信息" />
        </a-steps>

        <!-- 步骤一：选择入库类型 -->
        <div v-show="currentStep === 0">
          <a-row>
            <a-col :span="24">
              <a-form-item label="入库类型" :labelCol="{ span: 4 }" :wrapperCol="{ span: 16 }">
                <a-radio-group
                  v-decorator="['businessType', validatorRules.businessType]"
                  @change="handleBusinessTypeChange"
                >
                  <a-radio value="11">采购入库</a-radio>
                  <a-radio value="12">余料入库</a-radio>
                  <a-radio value="13">调拨入库</a-radio>
                  <a-radio value="19">其他入库</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>

          <!-- 采购入库特有字段 -->
          <template v-if="businessType === '11'">
            <a-row>
              <a-col :span="12">
                <a-form-item label="采购单号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select
                    v-decorator="['purchaseOrderNo', validatorRules.purchaseOrderNo]"
                    placeholder="请选择采购单号"
                    showSearch
                    :filterOption="false"
                    @search="handlePurchaseOrderSearch"
                    @change="handlePurchaseOrderChange"
                    :loading="purchaseOrderLoading"
                    optionFilterProp="children"
                    allowClear
                  >
                    <a-select-option
                      v-for="order in validPurchaseOrders"
                      :key="order.orderNo || order.id || 'empty'"
                      :value="order.orderNo"
                    >
                      {{ order.orderNo }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </template>

          <a-row>
            <a-col :span="12">
              <a-form-item label="业务单号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-decorator="['businessNo', validatorRules.businessNo]" placeholder="系统自动生成" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="批次号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-decorator="['batchNo']" placeholder="系统自动生成" disabled />
              </a-form-item>
            </a-col>
          </a-row>
        </div>

        <!-- 步骤二：物料信息 -->
        <div v-show="currentStep === 1">
          <!-- 调拨入库特有的源仓库选择和库存查询 -->
          <template v-if="businessType === '13'">
            <a-row>
              <a-col :span="24">
                <a-form-item label="源仓库" :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                  <a-row type="flex" :gutter="8">
                    <a-col :span="8">
                      <j-select-warehouse
                        v-model="sourceWarehouseId"
                        placeholder="请选择源仓库"
                        @change="handleSourceWarehouseChange"
                      />
                    </a-col>
                    <a-col :span="4">
                      <a-button type="primary" @click="querySourceInventory" :loading="sourceInventoryLoading"
                        >查询库存</a-button
                      >
                    </a-col>
                  </a-row>
                </a-form-item>
              </a-col>
            </a-row>

            <!-- 源仓库库存信息表格 -->
            <a-table
              v-if="sourceInventoryList.length > 0"
              :columns="sourceInventoryColumns"
              :dataSource="sourceInventoryList"
              :pagination="false"
              :rowSelection="{
                selectedRowKeys: selectedInventoryKeys,
                onChange: onSelectInventoryChange,
                type: 'checkbox',
              }"
              size="small"
              :scroll="{ y: 300, x: 1200 }"
              rowKey="id"
              style="margin-bottom: 16px"
              :sticky="true"
            >
              <template slot="availableQuantitySlot" slot-scope="text">
                <span :style="{ color: text <= 0 ? '#ff4d4f' : '' }">{{ text }}</span>
              </template>
              <template slot="transferQuantitySlot" slot-scope="text, record, index">
                <a-input-number
                  v-model="sourceInventoryList[index].transferQuantity"
                  :min="1"
                  :max="record.availableQuantity"
                  :precision="0"
                  style="width: 100px"
                  placeholder="调拨数量"
                />
              </template>
              <template slot="targetLocationSlot" slot-scope="text, record, index">
                <j-select-warehouse-location
                  v-model="sourceInventoryList[index].targetLocationId"
                  :warehouse-id="sourceInventoryList[index].targetWarehouseId"
                  placeholder="请选择目标库位"
                  @change="(value, option) => handleTargetLocationChange(record, value, option)"
                />
              </template>
              <template slot="targetWarehouseSlot" slot-scope="text, record, index">
                <j-select-warehouse
                  v-model="sourceInventoryList[index].targetWarehouseId"
                  placeholder="请选择目标仓库"
                  @change="(value, option) => handleTargetWarehouseChange(record, value, option)"
                />
              </template>
            </a-table>

            <!-- 添加到调拨列表按钮 -->
            <a-row v-if="sourceInventoryList.length > 0" style="margin-bottom: 16px">
              <a-col :span="24" style="text-align: right">
                <a-button type="primary" @click="addToTransferList" :disabled="selectedInventoryKeys.length === 0">
                  加入调拨物料列表
                </a-button>
              </a-col>
            </a-row>

            <!-- 已添加的调拨物料列表 -->
            <a-divider v-if="selectedMaterials.length > 0" orientation="left">调拨物料列表</a-divider>
            <a-table
              v-if="selectedMaterials.length > 0"
              :columns="transferMaterialColumns"
              :dataSource="selectedMaterials"
              :pagination="false"
              size="small"
              rowKey="id"
              :scroll="{ x: 1200 }"
              :sticky="true"
            >
              <template slot="actionSlot" slot-scope="text, record">
                <a-button type="danger" size="small" @click="removeTransferMaterial(record)">删除</a-button>
              </template>
            </a-table>
          </template>

          <!-- 非调拨入库的物料选择 -->
          <a-row v-if="businessType !== '13' && businessType !== '11' && !isSurplusMaterial">
            <a-col :span="24">
              <a-form-item label="物料" :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                <j-select-material
                  v-decorator="['materialId', validatorRules.materialId]"
                  mode="multiple"
                  :multiple="true"
                  @change="handleMultipleMaterialsChange"
                  placeholder="请选择物料"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <!-- 余料入库特有字段 -->
          <template v-if="businessType === '12'">
            <a-row>
              <a-col :span="12">
                <a-form-item label="订单编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select
                    v-decorator="['productionOrderId']"
                    placeholder="请选择订单编号"
                    @change="handleProductionOrderChange"
                    :loading="orderLoading"
                    showSearch
                    :filterOption="false"
                    @search="handleOrderSearch"
                    optionFilterProp="children"
                    allowClear
                  >
                    <a-select-option
                      v-for="order in validProductionOrders"
                      :key="order.id || order.orderNo || 'empty'"
                      :value="order.id"
                    >
                      {{ order.orderNo }} - {{ order.customerName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </template>

          <!-- 显示已选择的物料列表（非调拨入库模式） -->
          <div v-if="!isSurplusMaterial && businessType !== '13' && selectedMaterials.length > 0">
            <a-divider orientation="left">已选择物料</a-divider>
            <a-alert
              message="系统将根据物料类型自动推荐对应的仓库和库位"
              description="不同物料类型将会存放在不同的仓库中，系统会自动分配合适的库位。您也可以在下方表格中手动修改仓库和库位。"
              type="info"
              show-icon
              style="margin-bottom: 16px"
            />
            <a-row style="margin-bottom: 16px">
              <a-col :span="24">
                <a-button
                  type="primary"
                  @click="recommendWarehouseByMaterialType"
                  :disabled="selectedMaterials.length === 0"
                >
                  根据物料类型推荐库位
                </a-button>
              </a-col>
            </a-row>
            <a-table
              :columns="materialColumnsWithWarehouse"
              :dataSource="selectedMaterials"
              :pagination="false"
              size="small"
              rowKey="id"
              :scroll="{ y: 300, x: 1200 }"
              :sticky="true"
            >
              <template slot="materialTypeSlot" slot-scope="text">
                <j-dict-label :value="text" dictCode="material_type" />
              </template>
              <template slot="receivedQuantitySlot" slot-scope="text">
                <span :style="{ color: text > 0 ? '#1890ff' : '' }">{{ text || 0 }}</span>
              </template>
              <template slot="availableQuantitySlot" slot-scope="text">
                <span :style="{ color: text <= 0 ? '#ff4d4f' : '#52c41a' }">{{ text }}</span>
              </template>
              <template slot="quantity" slot-scope="text, record, index">
                <a-input-number
                  v-model="selectedMaterials[index].planQuantity"
                  :min="1"
                  :max="selectedMaterials[index].availableQuantity"
                  :step="1"
                  style="width: 100%"
                  @change="(value) => handleMaterialQuantityChange(record, value)"
                  placeholder="请输入数量"
                />
              </template>
              <template slot="unitCost" slot-scope="text, record, index">
                <a-input-number
                  v-model="selectedMaterials[index].unitCost"
                  :min="0"
                  :step="0.01"
                  :precision="2"
                  style="width: 100%"
                  placeholder="单位成本"
                />
              </template>
              <template slot="warehouseSelect" slot-scope="text, record, index">
                <a-select
                  v-model="selectedMaterials[index].warehouseId"
                  placeholder="请选择仓库"
                  style="width: 100%"
                  showSearch
                  optionFilterProp="children"
                  @change="(value, option) => handleWarehouseChangeForMaterial(record, value, option)"
                >
                  <a-select-option
                    v-for="warehouse in validWarehouseList"
                    :key="warehouse.id || warehouse.warehouseName || 'empty'"
                    :value="warehouse.id"
                  >
                    {{ warehouse.warehouseName }}
                    <span
                      v-if="warehouse.warehouseType === selectedMaterials[index].materialType"
                      style="color: #52c41a"
                    >
                      (推荐)</span
                    >
                  </a-select-option>
                  <a-select-option v-if="warehouseList.length === 0" disabled> 正在加载仓库数据... </a-select-option>
                </a-select>
              </template>
              <template slot="locationSelect" slot-scope="text, record, index">
                <j-select-warehouse-location
                  v-model="selectedMaterials[index].locationId"
                  :warehouse-id="selectedMaterials[index].warehouseId"
                  placeholder="请选择库位"
                  @change="(value, option) => handleLocationChange(record, value, option)"
                />
              </template>
            </a-table>
          </div>

          <div v-if="isSurplusMaterial">
            <a-table
              :columns="surplusMaterialColumnsWithWarehouse"
              :dataSource="selectedMaterials"
              :pagination="false"
              size="small"
              rowKey="materialCode"
              :scroll="{ y: 300, x: 1200 }"
              :sticky="true"
            >
              <template slot="materialTypeSlot" slot-scope="text">
                <j-dict-label :value="text" dictCode="material_type" />
              </template>
              <template slot="quantity" slot-scope="text, record, index">
                <a-input-number
                  v-model="selectedMaterials[index].planQuantity"
                  :min="1"
                  :step="1"
                  style="width: 100%"
                  @change="(value) => handleMaterialQuantityChange(record, value)"
                  placeholder="请输入数量"
                />
              </template>
              <template slot="unitCost" slot-scope="text, record, index">
                <a-input-number
                  v-model="selectedMaterials[index].unitCost"
                  :min="0"
                  :step="0.01"
                  :precision="2"
                  style="width: 100%"
                  placeholder="单位成本"
                />
              </template>
              <template slot="warehouseSelect" slot-scope="text, record, index">
                <a-select
                  v-model="selectedMaterials[index].warehouseId"
                  placeholder="请选择仓库"
                  style="width: 100%"
                  showSearch
                  optionFilterProp="children"
                  @change="(value, option) => handleWarehouseChangeForMaterial(record, value, option)"
                >
                  <a-select-option
                    v-for="warehouse in validWarehouseList"
                    :key="warehouse.id || warehouse.warehouseName || 'empty'"
                    :value="warehouse.id"
                  >
                    {{ warehouse.warehouseName }}
                    <span
                      v-if="warehouse.warehouseType === selectedMaterials[index].materialType"
                      style="color: #52c41a"
                    >
                      (推荐)</span
                    >
                  </a-select-option>
                  <a-select-option v-if="warehouseList.length === 0" disabled> 正在加载仓库数据... </a-select-option>
                </a-select>
              </template>
              <template slot="locationSelect" slot-scope="text, record, index">
                <j-select-warehouse-location
                  v-model="selectedMaterials[index].locationId"
                  :warehouse-id="selectedMaterials[index].warehouseId"
                  placeholder="请选择库位"
                  @change="(value, option) => handleLocationChange(record, value, option)"
                />
              </template>
            </a-table>
          </div>
        </div>

        <!-- 步骤三：入库信息 -->
        <div v-show="currentStep === 2">
          <a-row>
            <a-col :span="24">
              <a-alert
                message="入库信息提示"
                description="入库人员和实际入库时间将在实际入库确认时填写，此处仅需填写计划信息和备注。"
                type="info"
                show-icon
                style="margin-bottom: 16px"
              />
            </a-col>
          </a-row>

          <!-- 采购入库特有字段 -->
          <template v-if="businessType === '11'">
            <a-row>
              <a-col :span="24">
                <a-form-item label="采购单据" :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                  <j-upload v-decorator="['purchaseDocuments']" :fileType="'file'" :number="5" bizPath="wms/purchase" />
                </a-form-item>
              </a-col>
            </a-row>
          </template>

          <a-row>
            <a-col :span="24">
              <a-form-item label="备注" :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                <a-textarea v-decorator="['remark']" :rows="4" placeholder="请输入备注" />
              </a-form-item>
            </a-col>
          </a-row>

          <!-- 入库单基本信息 -->
          <a-divider orientation="left">入库单基本信息</a-divider>
          <a-descriptions bordered :column="2">
            <a-descriptions-item label="入库类型">{{ getBusinessTypeName() }}</a-descriptions-item>
            <a-descriptions-item label="业务单号">{{ form.getFieldValue('businessNo') }}</a-descriptions-item>
            <a-descriptions-item label="批次号">{{ form.getFieldValue('batchNo') }}</a-descriptions-item>
            <a-descriptions-item label="备注">{{ form.getFieldValue('remark') || '-' }}</a-descriptions-item>
            <a-descriptions-item v-if="businessType === '12'" label="生产订单编号">
              {{ getProductionOrderNo() || '-' }}
            </a-descriptions-item>
            <a-descriptions-item v-if="businessType === '11'" label="采购单号">
              {{ form.getFieldValue('purchaseOrderNo') || '-' }}
            </a-descriptions-item>
          </a-descriptions>

          <!-- 入库单预览 -->
          <a-divider orientation="left">入库单预览</a-divider>

          <div v-if="selectedMaterials.length > 0">
            <a-table
              :columns="
                isSurplusMaterial
                  ? surplusPreviewColumns
                  : businessType === '13'
                  ? transferPreviewColumns
                  : previewColumns
              "
              :dataSource="selectedMaterials"
              :pagination="false"
              size="small"
              :rowKey="isSurplusMaterial ? 'materialCode' : 'id'"
              :scroll="{ y: 300, x: 1200 }"
              :sticky="true"
            >
              <template slot="warehouseNameSlot" slot-scope="text, record">
                {{ record.warehouseName || '-' }}
                <span v-if="!record.warehouseName" style="color: #999; font-size: 12px">
                  (ID: {{ record.warehouseId || '无' }})
                </span>
              </template>
              <template slot="locationNameSlot" slot-scope="text, record">
                {{ record.locationName || '-' }}
                <span v-if="!record.locationName && record.locationId" style="color: #ff4d4f; font-size: 12px">
                  (ID: {{ record.locationId }})
                </span>
              </template>
              <template slot="sourceWarehouseNameSlot" slot-scope="text, record">
                {{ record.sourceWarehouseName || '-' }}
              </template>
              <template slot="sourceLocationNameSlot" slot-scope="text, record">
                {{ record.sourceLocationName || '-' }}
              </template>
            </a-table>
          </div>
        </div>

        <!-- 步骤按钮 -->
        <div style="margin-top: 24px; text-align: center">
          <a-button @click="prevStep" v-if="currentStep > 0" style="margin-right: 8px">上一步</a-button>
          <a-button type="primary" @click="nextStep" v-if="currentStep < 2">下一步</a-button>
        </div>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JSelectMaterial from '@/components/jeecgbiz/JSelectMaterial'
import JSelectWarehouse from '@/components/jeecgbiz/JSelectWarehouse'
import JSelectWarehouseLocation from '@/components/jeecgbiz/JSelectWarehouseLocation'
import JUpload from '@/components/jeecg/JUpload'
import { createInboundOrder, editInboundOrder, createSurplusInboundOrder } from '@/api/wms'
import {
  getQualifiedUnprocessedInspection,
  updateInspectionStatus,
  getMaterialArrivalQuantity,
} from '@/api/wms/purchase'

export default {
  name: 'InboundOrderModal',
  mixins: [JeecgListMixin],
  components: {
    JSelectMaterial,
    JSelectWarehouse,
    JSelectWarehouseLocation,
    JUpload,
  },
  data() {
    return {
      title: '新增入库单',
      visible: false,
      model: {}, // 添加model属性用于存储当前编辑的记录
      confirmLoading: false,
      disableSubmit: false, // 添加禁用提交按钮的属性
      form: this.$form.createForm(this),
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      // 提供一个空的url配置，防止JeecgListMixin的loadData方法报错
      url: {
        list: '',
      },
      validatorRules: {
        businessType: { rules: [{ required: true, message: '请选择业务类型!' }] },
        materialType: { rules: [{ required: true, message: '请选择物料类型!' }] },
        materialId: { rules: [{ required: true, message: '请选择物料!' }] },
        materialName: { rules: [{ required: true, message: '物料名称不能为空!' }] },
        planLocationId: { rules: [{ required: true, message: '请选择计划入库库位!' }] },
        planQuantity: { rules: [{ required: true, message: '请输入计划入库数量!' }] },
        unitCost: { rules: [{ required: true, message: '请输入单位成本!' }] },
        businessNo: { rules: [{ required: false, message: '系统自动生成业务单号' }] },
        purchaseOrderNo: { rules: [{ required: true, message: '请选择采购单号' }] },
        sourceMaterialId: { rules: [{ required: true, message: '请选择原型材!' }] },
        surplusLength: { rules: [{ required: true, message: '请输入余料长度!' }] },
        sourceMaterialType: { rules: [{ required: true, message: '请选择原型材类型!' }] },
      },
      currentStep: 0,
      materialType: '',
      businessType: '',
      warehouseId: '',
      warehouseIds: [], // 多选仓库ID数组
      warehouseName: '',
      locationName: '',
      productionOrders: [],
      orderLoading: false,
      purchaseOrders: [], // 采购单列表
      purchaseOrderLoading: false, // 采购单加载状态
      sourceMaterialType: '1',
      sourceMaterialInfo: {},
      materialInfo: {},
      // 多物料相关
      selectedMaterials: [], // 已选择的物料列表
      // 物料列表表格列
      materialColumns: [
        { title: '物料编码', dataIndex: 'materialCode', width: 120 },
        { title: '物料名称', dataIndex: 'materialName', width: 150 },
        { title: '物料类型', dataIndex: 'materialType', width: 100, scopedSlots: { customRender: 'materialTypeSlot' } },
        { title: '规格', dataIndex: 'specification', width: 120 },
        { title: '单位', dataIndex: 'unit', width: 80 },
        { title: '计划入库数量', dataIndex: 'planQuantity', width: 120, scopedSlots: { customRender: 'quantity' } },
        { title: '单位成本', dataIndex: 'unitCost', width: 120, scopedSlots: { customRender: 'unitCost' } },
        // { title: '操作', dataIndex: 'action', width: 80, scopedSlots: { customRender: 'action' } }
      ],
      // 库位分配表格列
      locationColumns: [
        { title: '物料编码', dataIndex: 'materialCode', width: 120 },
        { title: '物料名称', dataIndex: 'materialName', width: 150 },
        { title: '物料类型', dataIndex: 'materialType', width: 100, scopedSlots: { customRender: 'materialTypeSlot' } },
        { title: '仓库', dataIndex: 'warehouseId', width: 150, scopedSlots: { customRender: 'warehouseSelect' } },
        { title: '库位', dataIndex: 'locationId', width: 150, scopedSlots: { customRender: 'locationSelect' } },
        { title: '计划入库数量', dataIndex: 'planQuantity', width: 120, scopedSlots: { customRender: 'quantity' } },
        // 移除预警上限和预警下限列
      ],
      // 余料库位分配表格列
      surplusLocationColumns: [
        { title: '物料编码', dataIndex: 'materialCode', width: 120 },
        { title: '型材编码', dataIndex: 'profileCode', width: 120 },
        { title: '型材名称', dataIndex: 'profileName', width: 150 },
        { title: '余料长度', dataIndex: 'surplusLength', width: 100 },
        { title: '物料类型', dataIndex: 'materialType', width: 100, scopedSlots: { customRender: 'materialTypeSlot' } },
        { title: '仓库', dataIndex: 'warehouseId', width: 150, scopedSlots: { customRender: 'warehouseSelect' } },
        { title: '库位', dataIndex: 'locationId', width: 150, scopedSlots: { customRender: 'locationSelect' } },
        { title: '计划入库数量', dataIndex: 'planQuantity', width: 100, scopedSlots: { customRender: 'quantity' } },
        // 移除预警上限和预警下限列
      ],
      // 预览表格列
      previewColumns: [
        { title: '物料编码', dataIndex: 'materialCode', width: 120 },
        { title: '物料名称', dataIndex: 'materialName', width: 150 },
        { title: '规格', dataIndex: 'specification', width: 120 },
        { title: '单位', dataIndex: 'unit', width: 80 },
        {
          title: '入库仓库',
          dataIndex: 'warehouseName',
          width: 120,
          scopedSlots: { customRender: 'warehouseNameSlot' },
        },
        { title: '入库库位', dataIndex: 'locationName', width: 120, scopedSlots: { customRender: 'locationNameSlot' } },
        { title: '计划入库数量', dataIndex: 'planQuantity', width: 120 },
        { title: '单位成本', dataIndex: 'unitCost', width: 120 },
      ],
      // 余料预览表格列
      surplusPreviewColumns: [
        { title: '物料编码', dataIndex: 'materialCode', width: 120 },
        { title: '型材编码', dataIndex: 'profileCode', width: 120 },
        { title: '型材名称', dataIndex: 'profileName', width: 150 },
        { title: '余料长度', dataIndex: 'surplusLength', width: 100 },
        {
          title: '入库仓库',
          dataIndex: 'warehouseName',
          width: 120,
          scopedSlots: { customRender: 'warehouseNameSlot' },
        },
        { title: '入库库位', dataIndex: 'locationName', width: 120, scopedSlots: { customRender: 'locationNameSlot' } },
        { title: '计划入库数量', dataIndex: 'planQuantity', width: 120 },
        { title: '单位成本', dataIndex: 'unitCost', width: 120 },
      ],
      // 调拨入库预览表格列
      transferPreviewColumns: [
        { title: '物料编码', dataIndex: 'materialCode', width: 120 },
        { title: '物料名称', dataIndex: 'materialName', width: 150 },
        { title: '规格', dataIndex: 'specification', width: 120 },
        { title: '单位', dataIndex: 'unit', width: 80 },
        {
          title: '源仓库',
          dataIndex: 'sourceWarehouseName',
          width: 120,
          scopedSlots: { customRender: 'sourceWarehouseNameSlot' },
        },
        {
          title: '源库位',
          dataIndex: 'sourceLocationName',
          width: 120,
          scopedSlots: { customRender: 'sourceLocationNameSlot' },
        },
        {
          title: '入库仓库',
          dataIndex: 'warehouseName',
          width: 120,
          scopedSlots: { customRender: 'warehouseNameSlot' },
        },
        { title: '入库库位', dataIndex: 'locationName', width: 120, scopedSlots: { customRender: 'locationNameSlot' } },
        { title: '计划入库数量', dataIndex: 'planQuantity', width: 120 },
        { title: '单位成本', dataIndex: 'unitCost', width: 120 },
        { title: '批次号', dataIndex: 'batchNo', width: 120 },
      ],
      warehouseNameMap: {}, // 仓库名称缓存
      warehouseList: [], // 仓库列表
      warehouseTypeMap: {
        // 仓库类型映射
        1: '1', // 型材库(1)只能存放型材(1)
        2: '2', // 配件库(2)只能存放配件(2)
        3: '3', // 辅件库(3)只能存放辅件(3)
        4: '4', // 其他库(4)只能存放其他物料(4)
        5: '5', // 余料库(5)只能存放余料(5)
        6: '6', // 半料库(6)只能存放半料(6)
      },

      // 是否余料模式
      isSurplusMaterial: false,

      // 余料相关
      productionOrders: [],
      orderLoading: false,
      surplusMaterials: [],
      groupedSurplusMaterials: [],

      // 余料表格列
      surplusMaterialColumns: [
        { title: '物料编码', dataIndex: 'materialCode', width: 120 },
        { title: '型材编码', dataIndex: 'profileCode', width: 120 },
        { title: '型材名称', dataIndex: 'profileName', width: 150 },
        { title: '余料长度', dataIndex: 'surplusLength', width: 100 },
        { title: '规格', dataIndex: 'specification', width: 120 },
        { title: '单位', dataIndex: 'unit', width: 80 },
        { title: '物料类型', dataIndex: 'materialType', width: 100, scopedSlots: { customRender: 'materialTypeSlot' } },
        { title: '计划入库数量', dataIndex: 'planQuantity', width: 120, scopedSlots: { customRender: 'quantity' } },
        { title: '单位成本', dataIndex: 'unitCost', width: 120, scopedSlots: { customRender: 'unitCost' } },
      ],

      // 调拨入库相关
      sourceWarehouseId: '', // 源仓库ID
      sourceWarehouseName: '', // 源仓库名称
      sourceInventoryList: [], // 源仓库库存列表
      sourceInventoryLoading: false, // 源仓库库存加载状态
      selectedInventoryKeys: [], // 选中的库存记录ID
      selectedInventoryRows: [], // 选中的库存记录

      // 源仓库库存表格列
      sourceInventoryColumns: [
        { title: '物料编码', dataIndex: 'materialCode', width: 120 },
        { title: '物料名称', dataIndex: 'materialName', width: 150 },
        { title: '规格', dataIndex: 'specification', width: 120 },
        { title: '单位', dataIndex: 'unit', width: 80 },
        {
          title: '可用库存',
          dataIndex: 'availableQuantity',
          width: 100,
          scopedSlots: { customRender: 'availableQuantitySlot' },
        },
        { title: '库位', dataIndex: 'locationName', width: 100 },
        { title: '批次号', dataIndex: 'batchNo', width: 120 },
        {
          title: '调拨数量',
          dataIndex: 'transferQuantity',
          width: 120,
          scopedSlots: { customRender: 'transferQuantitySlot' },
        },
        {
          title: '目标仓库',
          dataIndex: 'targetWarehouseId',
          width: 150,
          scopedSlots: { customRender: 'targetWarehouseSlot' },
        },
        {
          title: '目标库位',
          dataIndex: 'targetLocationId',
          width: 150,
          scopedSlots: { customRender: 'targetLocationSlot' },
        },
      ],

      // 调拨物料列表表格列
      transferMaterialColumns: [
        { title: '物料编码', dataIndex: 'materialCode', width: 120 },
        { title: '物料名称', dataIndex: 'materialName', width: 150 },
        { title: '规格', dataIndex: 'specification', width: 120 },
        { title: '单位', dataIndex: 'unit', width: 80 },
        { title: '调拨数量', dataIndex: 'planQuantity', width: 100 },
        { title: '源仓库', dataIndex: 'sourceWarehouseName', width: 120 },
        { title: '源库位', dataIndex: 'sourceLocationName', width: 120 },
        { title: '目标仓库', dataIndex: 'warehouseName', width: 120 },
        { title: '目标库位', dataIndex: 'locationName', width: 120 },
        { title: '批次号', dataIndex: 'batchNo', width: 120 },
        { title: '操作', dataIndex: 'action', width: 80, scopedSlots: { customRender: 'actionSlot' } },
      ],

      // 物料列表表格列（带仓库库位）
      materialColumnsWithWarehouse: [
        { title: '物料编码', dataIndex: 'materialCode', width: 120 },
        { title: '物料名称', dataIndex: 'materialName', width: 150 },
        { title: '物料类型', dataIndex: 'materialType', width: 100, scopedSlots: { customRender: 'materialTypeSlot' } },
        { title: '规格', dataIndex: 'specification', width: 120 },
        { title: '单位', dataIndex: 'unit', width: 80 },
        { title: '采购数量', dataIndex: 'originalQuantity', width: 100 },
        // { title: '已到货数量', dataIndex: 'receivedQuantity', width: 100, scopedSlots: { customRender: 'receivedQuantitySlot' } },
        {
          title: '可入库数量',
          dataIndex: 'availableQuantity',
          width: 100,
          scopedSlots: { customRender: 'availableQuantitySlot' },
        },
        { title: '计划入库数量', dataIndex: 'planQuantity', width: 120, scopedSlots: { customRender: 'quantity' } },
        { title: '单位成本', dataIndex: 'unitCost', width: 120, scopedSlots: { customRender: 'unitCost' } },
        { title: '仓库', dataIndex: 'warehouseId', width: 150, scopedSlots: { customRender: 'warehouseSelect' } },
        { title: '库位', dataIndex: 'locationId', width: 150, scopedSlots: { customRender: 'locationSelect' } },
      ],

      // 余料表格列（带仓库库位）
      surplusMaterialColumnsWithWarehouse: [
        { title: '物料编码', dataIndex: 'materialCode', width: 120 },
        { title: '型材编码', dataIndex: 'profileCode', width: 120 },
        { title: '型材名称', dataIndex: 'profileName', width: 150 },
        { title: '余料长度', dataIndex: 'surplusLength', width: 100 },
        { title: '规格', dataIndex: 'specification', width: 120 },
        { title: '单位', dataIndex: 'unit', width: 80 },
        { title: '物料类型', dataIndex: 'materialType', width: 100, scopedSlots: { customRender: 'materialTypeSlot' } },
        { title: '计划入库数量', dataIndex: 'planQuantity', width: 120, scopedSlots: { customRender: 'quantity' } },
        { title: '单位成本', dataIndex: 'unitCost', width: 120, scopedSlots: { customRender: 'unitCost' } },
        { title: '仓库', dataIndex: 'warehouseId', width: 150, scopedSlots: { customRender: 'warehouseSelect' } },
        { title: '库位', dataIndex: 'locationId', width: 150, scopedSlots: { customRender: 'locationSelect' } },
      ],
      purchaseOrderId: '', // 当前选中的采购单ID，用于更新执行状态
      inspectionIds: [], // 用于存储质检记录ID，入库成功后更新状态
      materialArrivalQuantity: {}, // 物料已到货数量 {materialId: receivedQuantity}
    }
  },
  computed: {
    // 过滤有效的采购单列表
    validPurchaseOrders() {
      return (this.purchaseOrders || []).filter((order) => order && order.orderNo)
    },
    // 过滤有效的生产订单列表
    validProductionOrders() {
      return (this.productionOrders || []).filter((order) => order && order.id)
    },
    // 过滤有效的仓库列表
    validWarehouseList() {
      return (this.warehouseList || []).filter((warehouse) => warehouse && warehouse.id && warehouse.warehouseName)
    },
  },
  methods: {
    // 覆盖JeecgListMixin中的loadData方法，避免不必要的API调用
    loadData() {
      // 模态框不需要加载列表数据，所以这里不做任何操作
      console.log('InboundOrderModal组件不需要加载列表数据')
    },

    add() {
      this.resetModal()
      this.visible = true
      this.disableSubmit = false
      this.title = '新增入库单' // 明确设置标题
      this.model = {} // 清空model对象，确保不会进入编辑模式

      // 加载仓库名称缓存
      this.loadWarehouseNames().catch((err) => {
        console.error('加载仓库数据失败:', err)
      })
    },

    // 添加编辑方法
    edit(record) {
      this.resetModal()
      this.visible = true

      // 记录当前记录ID
      this.model = Object.assign({}, record) // 使用对象复制防止引用修改
      this.businessType = record.businessType + '' // 确保类型是字符串

      // 如果是禁用提交的模式，说明是查看详情
      if (this.disableSubmit) {
        this.title = '入库单详情'
        // 设置为最后一步，直接显示预览
        this.currentStep = 3
      } else {
        this.title = '编辑入库单'
        this.disableSubmit = false
      }

      console.log('编辑入库单:', this.model.id) // 打印日志以便确认进入编辑模式

      // 加载入库单明细
      this.loadInboundOrderDetails(record.id)

      // 加载仓库名称缓存
      this.loadWarehouseNames()

      // 设置表单数据
      this.$nextTick(() => {
        // 确保businessType被正确设置为字符串类型
        const businessTypeStr = record.businessType + ''

        // 基本表单字段设置
        const formValues = {
          businessType: businessTypeStr,
          businessNo: record.businessNo,
          batchNo: record.batchNo,
          supplier: record.supplier,
          remark: record.remark,
        }

        // 根据业务类型设置特定字段
        if (businessTypeStr === '11') {
          // 采购入库
          formValues.purchaseOrderNo = record.purchaseOrderNo
        } else if (businessTypeStr === '13') {
          // 调拨入库
          formValues.sourceWarehouseId = record.sourceWarehouseId
        }

        // 设置表单值
        this.form.setFieldsValue(formValues)

        console.log('编辑时设置的业务类型:', businessTypeStr)
        console.log('编辑时设置的表单值:', formValues)

        // 如果是查看详情模式，禁用所有表单项
        if (this.disableSubmit) {
          setTimeout(() => {
            const formItems = document.querySelectorAll('.ant-form-item-control')
            formItems.forEach((item) => {
              const inputs = item.querySelectorAll('input, textarea, .ant-select, .ant-radio-group')
              inputs.forEach((input) => {
                input.setAttribute('disabled', 'disabled')
              })
            })
          }, 100)
        }
      })
    },

    // 加载入库单明细
    loadInboundOrderDetails(inboundOrderId) {
      if (!inboundOrderId) return

      this.confirmLoading = true
      getAction('/wms/inboundOrder/queryDetailList', { inboundOrderId: inboundOrderId })
        .then((res) => {
          if (res.success) {
            const details = res.result || []

            // 将明细转换为selectedMaterials格式
            this.selectedMaterials = details.map((detail, index) => ({
              id: detail.materialId || detail.id || `temp_${index}`, // 确保id不为null
              materialCode: detail.materialCode,
              materialName: detail.materialName,
              materialType: detail.materialType,
              specification: detail.specification,
              color: detail.color,
              unit: detail.unit,
              planQuantity: detail.planQuantity,
              actualQuantity: detail.actualQuantity,
              unitCost: detail.unitCost,
              totalCost: detail.totalCost,
              warehouseId: detail.planWarehouseId,
              warehouseName: detail.planWarehouseName,
              locationId: detail.planLocationId,
              locationName: detail.planLocationName,
              upperLimit: detail.upperLimit,
              lowerLimit: detail.lowerLimit,
              detailId: detail.id, // 保存明细ID，用于更新
            }))

            // 更新物料的仓库名称
            this.updateMaterialsWarehouseName()

            console.log('加载入库单明细成功:', this.selectedMaterials.length, '个物料')
          } else {
            this.$message.error(res.message || '加载入库单明细失败')
          }
        })
        .catch((err) => {
          console.error('加载入库单明细异常:', err)
          this.$message.error('加载入库单明细异常')
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },

    // 重置模态框
    resetModal() {
      this.form.resetFields()
      this.model = {} // 清空model对象，防止编辑模式
      this.currentStep = 0
      this.businessType = ''
      this.warehouseId = ''
      this.warehouseIds = [] // 重置多选仓库ID数组
      this.warehouseName = ''
      this.locationName = ''
      this.productionOrders = []
      this.sourceMaterialType = '1'
      this.sourceMaterialInfo = {}
      this.materialInfo = {}
      this.selectedMaterials = [] // 重置已选择的物料列表
      this.surplusMaterials = [] // 重置余料列表
      this.groupedSurplusMaterials = [] // 重置分组后的余料列表
      this.isSurplusMaterial = false // 重置余料模式标志
      this.purchaseOrderId = '' // 重置当前选中的采购单ID
      this.inspectionIds = [] // 重置质检记录ID列表
      this.materialArrivalQuantity = {} // 重置已到货数量

      // 清除调拨入库相关数据
      this.sourceInventoryList = []
      this.selectedInventoryKeys = []
      this.selectedInventoryRows = []
      this.sourceWarehouseId = ''
      this.sourceWarehouseName = ''

      // 确保物料选择组件也被重置
      this.$nextTick(() => {
        const selectComponent = this.getMaterialSelectComponent()
        if (selectComponent) {
          selectComponent.selectedMaterialNames = ''
          selectComponent.selectedMaterialKeys = []
          selectComponent.selectedRowKeys = []
          selectComponent.selectedMaterials = []
        }
      })
    },

    // 下一步
    nextStep() {
      this.validateCurrentStep()
        .then((values) => {
          // 如果是采购入库且在第一步
          if (this.currentStep === 0 && this.businessType === '11') {
            const purchaseOrderNo = this.form.getFieldValue('purchaseOrderNo')
            if (!purchaseOrderNo) {
              this.$message.warning('请选择采购单号')
              return
            }

            // 由于在选择采购单号时已经加载了质检合格的物料，这里直接进入下一步
            // 检查是否已经加载了物料
            if (this.selectedMaterials.length === 0) {
              this.$message.warning('该采购单没有可入库的质检合格物料')
              return
            }

            this.currentStep++ // 进入下一步
          } else {
            // 其他类型直接进入下一步
            this.currentStep++

            // 如果进入物料分配库位步骤，尝试推荐库位
            if (this.currentStep === 2 && this.selectedMaterials.length > 0) {
              this.recommendLocationsByMaterialTypes()
            }
          }
        })
        .catch((err) => {
          console.error('验证当前步骤失败:', err)
        })
    },

    // 上一步
    prevStep() {
      if (this.currentStep > 0) {
        this.currentStep--
      }
    },

    // 验证当前步骤
    validateCurrentStep() {
      return new Promise((resolve, reject) => {
        // 根据当前步骤验证不同的字段
        let fieldsToValidate = []

        switch (this.currentStep) {
          case 0: // 第一步：业务类型
            fieldsToValidate = ['businessType']
            console.log('第一步验证字段:', fieldsToValidate, '当前业务单号:', this.form.getFieldValue('businessNo'))
            if (this.businessType === '13') {
              fieldsToValidate.push('sourceWarehouseId')
            }
            break
          case 1: // 第二步：物料信息
            // 只有在余料模式下才验证余料相关字段
            if (this.isSurplusMaterial) {
              // 余料模式下，只需验证是否有选择订单
              if (this.selectedMaterials.length === 0) {
                this.$message.warning('请选择订单并加载余料信息')
                return Promise.reject()
              }
            } else {
              // 如果有选择物料，则不需要验证materialId
              if (this.selectedMaterials.length === 0) {
                fieldsToValidate.push('materialId')
              }
            }
            break
          case 2: // 第三步：入库信息
            // 更新物料的仓库名称，确保预览时能显示正确的名称
            this.updateMaterialsWarehouseName()
            break
        }

        this.form.validateFields(fieldsToValidate, (errors, values) => {
          if (errors) {
            reject(errors)
          } else {
            resolve(values)
          }
        })
      }).catch((err) => {
        console.log('表单验证失败:', err)
        return Promise.reject(err)
      })
    },

    handleCancel() {
      console.log('关闭入库单弹窗，业务单号：', this.form.getFieldValue('businessNo'))
      this.visible = false
      this.resetModal()
      // 清除余料相关数据
      this.surplusMaterials = []
      this.groupedSurplusMaterials = []
      // 清除调拨入库相关数据
      this.sourceInventoryList = []
      this.selectedInventoryKeys = []
      this.selectedInventoryRows = []
      // 清除源仓库信息
      this.sourceWarehouseId = ''
      this.sourceWarehouseName = ''
    },

    handleOk() {
      if (this.currentStep < 2) {
        this.nextStep()
        return
      }

      const form = this.form
      this.confirmLoading = true
      form.validateFields((err, values) => {
        if (err) {
          this.confirmLoading = false
          return
        }

        // 构建入库单对象
        const inboundOrder = {
          id: this.model.id,
          businessType: values.businessType,
          businessNo: values.businessNo,
          batchNo: values.batchNo,
          inboundNo: values.inboundNo,
          planInboundTime: values.planInboundTime,
          remark: values.remark,
          status: this.model.status || 1,
          isSurplus: values.businessType === '12', // 设置是否余料标识
        }

        // 添加业务类型特有字段
        if (values.businessType === '11') {
          // 采购入库特有字段
          inboundOrder.purchaseOrderNo = values.purchaseOrderNo // 采购单号
          inboundOrder.purchaseOrderId = this.purchaseOrderId // 采购单ID
          inboundOrder.supplier = values.supplier
        } else if (values.businessType === '12') {
          inboundOrder.productionOrderId = values.productionOrderId
        } else if (values.businessType === '13') {
          inboundOrder.sourceWarehouseId = this.sourceWarehouseId || values.sourceWarehouseId
        } else if (values.businessType === '19') {
          // 其他入库类型特有字段
        }

        // 添加物料列表
        inboundOrder.materialList = this.selectedMaterials.map((item) => {
          const material = {
            materialId: item.id, // 确保传递物料ID
            materialCode: item.materialCode,
            materialName: item.materialName,
            materialType: item.materialType || '4', // 确保传递物料类型，默认为其他(4)
            specification: item.specification,
            unit: item.unit,
            planQuantity: item.planQuantity,
            unitCost: item.unitCost,
            planWarehouseId: item.warehouseId,
            planWarehouseName: item.warehouseName,
            planLocationId: item.locationId,
            planLocationName: item.locationName,
          }

          // 如果是编辑状态，传递明细ID
          if (item.detailId) {
            material.id = item.detailId
          }

          // 余料特有字段
          if (values.businessType === '12') {
            material.surplusLength = item.surplusLength
            material.profileCode = item.profileCode
            material.profileName = item.profileName
          }

          // 调拨入库特有字段
          if (values.businessType === '13') {
            material.sourceWarehouseId = item.sourceWarehouseId
            material.sourceWarehouseName = item.sourceWarehouseName
            material.sourceLocationId = item.sourceLocationId
            material.sourceLocationName = item.sourceLocationName
            material.batchNo = item.batchNo
          }

          return material
        })

        // 根据操作类型选择API方法
        let apiMethod

        if (this.model.id) {
          // 编辑模式
          console.log('使用编辑模式API，ID:', this.model.id)
          apiMethod = editInboundOrder
        } else if (values.businessType === '12') {
          // 新增余料入库
          console.log('使用新增余料入库API')
          apiMethod = createSurplusInboundOrder
        } else {
          // 新增普通入库单
          console.log('使用新增普通入库API')
          apiMethod = createInboundOrder
        }

        apiMethod(inboundOrder)
          .then((res) => {
            if (res.success) {
              this.$message.success(res.message || (this.model.id ? '编辑成功' : '添加成功'))

              // 如果是采购入库，且有质检记录ID，更新质检记录状态
              if (values.businessType === '11' && this.inspectionIds.length > 0) {
                updateInspectionStatus(this.inspectionIds.join(','))
                  .then((updateRes) => {
                    if (updateRes.success) {
                      console.log('质检记录状态已更新为已处理')
                    } else {
                      console.warn('更新质检记录状态失败:', updateRes.message)
                    }
                  })
                  .catch((err) => {
                    console.error('更新质检记录状态异常:', err)
                  })
              }

              this.$emit('ok')
              this.handleCancel()
            } else {
              this.$message.error(res.message || (this.model.id ? '编辑失败' : '添加失败'))
            }
          })
          .catch((err) => {
            console.error('提交入库单失败:', err)
            this.$message.error('提交入库单失败: ' + (err.message || '未知错误'))
          })
          .finally(() => {
            this.confirmLoading = false
          })
      })
    },

    // 业务类型变更处理
    handleBusinessTypeChange(e) {
      this.businessType = e.target.value
      this.form.resetFields(['productionOrderId', 'purchaseOrderNo', 'sourceWarehouseId'])

      // 生成当前日期时间字符串，格式为：年月日时分秒
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hour = String(now.getHours()).padStart(2, '0')
      const minute = String(now.getMinutes()).padStart(2, '0')
      const second = String(now.getSeconds()).padStart(2, '0')
      const dateStr = `${year}${month}${day}${hour}${minute}${second}`

      // 生成随机数，用于区分同一时间创建的单据
      const randomNum = Math.floor(Math.random() * 1000)
        .toString()
        .padStart(3, '0')

      // 批次号格式：PC + 年月日时分秒 + 3位随机数
      const batchNo = `PC${dateStr}${randomNum}`

      // 根据业务类型设置相关逻辑
      switch (this.businessType) {
        case '11': // 采购入库
          this.isSurplusMaterial = false
          // 初始加载采购单列表
          this.loadPurchaseOrders()
          // 采购入库的业务单号由采购单号填充，这里先清空
          this.form.setFieldsValue({
            businessNo: '',
            batchNo: batchNo
          })
          break
        case '12': // 余料入库
          this.isSurplusMaterial = true
          // 加载生产订单列表
          this.loadProductionOrders()
          // 余料入库的业务单号是订单编号，这里先清空，等选择订单后填充
          this.form.setFieldsValue({
            businessNo: '',
            batchNo: batchNo
          })
          break
        case '13': // 调拨入库
          this.isSurplusMaterial = false
          // 调拨入库无关联业务单号
          this.form.setFieldsValue({
            businessNo: '',
            batchNo: batchNo
          })
          break
        case '19': // 其他入库
          this.isSurplusMaterial = false
          // 其他入库无关联业务单号
          this.form.setFieldsValue({
            businessNo: '',
            batchNo: batchNo
          })
          break
        default:
          this.isSurplusMaterial = false
          this.form.setFieldsValue({
            businessNo: '',
            batchNo: batchNo
          })
      }
    },

    // 订单编号选择变更处理
    handleProductionOrderChange(orderId) {
      if (!orderId) {
        this.surplusMaterials = []
        this.selectedMaterials = []
        // 清空业务单号
        this.form.setFieldsValue({
          businessNo: ''
        })
        return
      }

      // 查找选中的订单信息
      const selectedOrder = this.productionOrders.find(order => order.id === orderId)
      if (selectedOrder && selectedOrder.orderNo) {
        // 设置业务单号为订单编号
        this.form.setFieldsValue({
          businessNo: selectedOrder.orderNo
        })
      }

      // 调用接口获取余料信息
      this.confirmLoading = true
      getAction('/wms/surplusMaterial/getByOrderId', {
        orderId: orderId,
      })
        .then((res) => {
          if (res.success) {
            // 处理余料数据
            this.surplusMaterials = res.result || []

            // 将余料信息转换为物料列表格式
            this.selectedMaterials = this.surplusMaterials.map((item) => {
              return {
                materialCode: item.materialCode || `${item.profileCode}-${item.surplusLength}`,
                materialName: item.profileName ? `${item.profileName}-${item.surplusLength}` : '余料',
                materialType: item.materialType || '5', // 余料类型
                specification: item.specification || '',
                unit: item.unit,
                planQuantity: parseInt(item.num) || 1, // 使用num字段作为计划数量
                unitCost: item.unitCost || 0,
                key: item.materialCode || `${item.profileCode}-${item.surplusLength}`, // 表格行key
                warehouseId: '',
                locationId: '',
                upperLimit: '',
                lowerLimit: '',
                surplusLength: item.surplusLength,
                profileCode: item.profileCode,
                profileName: item.profileName,
              }
            })

            // 对相同编号的余料进行数量统计
            this.processAndGroupSurplusMaterials()

            console.log('成功获取余料信息:', this.selectedMaterials.length, '个物料')

            // 自动加载仓库数据
            this.loadWarehouseNames().then(() => {
              // 自动调用推荐库位方法
              this.$nextTick(() => {
                if (this.selectedMaterials.length > 0) {
                  this.recommendWarehouseByMaterialType()
                }
              })
            })
          } else {
            this.$message.warning(res.message || '获取余料信息失败')
          }
        })
        .catch((err) => {
          console.error('获取余料信息异常:', err)
          this.$message.error('获取余料信息异常')
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },

    // 处理并分组余料信息
    processAndGroupSurplusMaterials() {
      const materialMap = new Map()

      // 遍历所有余料
      this.surplusMaterials.forEach((material) => {
        const materialCode = material.materialCode || `${material.profileCode}-${material.surplusLength}`

        if (materialMap.has(materialCode)) {
          // 如果已存在相同编号的余料，数量累加
          const existMaterial = materialMap.get(materialCode)
          existMaterial.planQuantity += parseInt(material.num) || 1
        } else {
          // 否则新增一条记录
          materialMap.set(materialCode, {
            materialCode: materialCode,
            materialName: material.profileName ? `${material.profileName}-${material.surplusLength}` : '余料',
            materialType: material.materialType || '5',
            specification: material.specification || '',
            unit: material.unit,
            planQuantity: parseInt(material.num) || 1,
            unitCost: material.unitCost || 0,
            key: materialCode,
            warehouseId: '',
            locationId: '',
            upperLimit: '',
            lowerLimit: '',
            surplusLength: material.surplusLength,
            profileCode: material.profileCode,
            profileName: material.profileName,
          })
        }
      })

      // 转换为数组
      this.selectedMaterials = Array.from(materialMap.values())
    },

    // 余料信息变更处理
    handleSurplusMaterialsChange(materials) {
      if (!materials || materials.length === 0) {
        this.selectedMaterials = []
        return
      }

      // 将余料信息转换为物料列表格式
      this.selectedMaterials = materials.map((item) => {
        return {
          materialCode: item.materialCode,
          materialName: item.materialName || (item.profileName ? item.profileName + '-' + item.surplusLength : '余料'),
          materialType: item.materialType || '5', // 余料类型
          specification: item.specification || '',
          unit: item.unit,
          planQuantity: item.planQuantity || 1,
          unitCost: item.unitCost || 0,
          key: item.materialCode, // 表格行key
          warehouseId: '',
          locationId: '',
          upperLimit: '',
          lowerLimit: '',
          surplusLength: item.surplusLength,
          profileCode: item.profileCode,
        }
      })
    },

    // 物料选择变更 (多选)
    handleMultipleMaterialsChange(value, materials) {
      // 获取选中的物料详细信息
      if (!value || !materials || !Array.isArray(materials) || materials.length === 0) {
        this.selectedMaterials = []
        return
      }

      // 处理选中的物料信息
      const selectedMaterialsData = materials.map((material) => {
        // 初始化时设置默认值
        return {
          ...material,
          planQuantity: 1, // 默认数量为1
          unitCost: material.unitCost || 0, // 保留原单位成本
          // 移除预警上限和预警下限默认值
          warehouseId: undefined, // 初始化仓库ID
          warehouseName: '', // 初始化仓库名称
          locationId: undefined, // 初始化库位ID
          locationName: '', // 初始化库位名称
        }
      })

      this.selectedMaterials = selectedMaterialsData

      // 设置隐藏字段materialId，用于表单验证
      if (selectedMaterialsData.length > 0) {
        this.form.setFieldsValue({
          materialId: value, // 设置物料ID以通过验证
        })
      }

      // 确保仓库数据已加载，然后尝试根据物料类型推荐仓库
      this.loadWarehouseNames()
        .then(() => {
          this.$nextTick(() => {
            if (this.selectedMaterials.length > 0) {
              this.recommendWarehouseByMaterialType()
            }
          })
        })
        .catch((err) => {
          console.error('加载仓库数据失败:', err)
        })
    },

    // 移除物料
    removeMaterial(record) {
      const index = this.selectedMaterials.findIndex((item) => item.id === record.id)
      if (index > -1) {
        this.selectedMaterials.splice(index, 1)

        // 更新表单中的materialId值
        if (this.selectedMaterials.length > 0) {
          const materialIds = this.selectedMaterials.map((item) => item.id).join(',')
          this.form.setFieldsValue({
            materialId: materialIds,
          })
        } else {
          this.form.setFieldsValue({
            materialId: undefined,
          })
        }

        // 强制更新j-select-material组件的显示
        this.$nextTick(() => {
          const selectComponent = this.getMaterialSelectComponent()
          if (selectComponent) {
            // 更新组件的selectedMaterialNames属性
            selectComponent.selectedMaterialNames = this.selectedMaterials.map((item) => item.materialName).join(',')
            selectComponent.selectedMaterialKeys = this.selectedMaterials.map((item) => item.id)
            selectComponent.selectedRowKeys = selectComponent.selectedMaterialKeys
            selectComponent.selectedMaterials = [...this.selectedMaterials]
          }
        })
      }
    },

    // 获取物料选择组件实例
    getMaterialSelectComponent() {
      // 获取当前表单中的j-select-material组件实例
      const jSelectMaterialRef = this.form.getFieldInstance('materialId')
      if (jSelectMaterialRef && jSelectMaterialRef.$children && jSelectMaterialRef.$children[0]) {
        return jSelectMaterialRef.$children[0]
      }
      return null
    },

    // 物料数量变更
    handleMaterialQuantityChange(record, value) {
      // 限制入库数量不超过可入库数量
      if (value > record.availableQuantity) {
        this.$message.warning(`入库数量不能超过可入库数量 ${record.availableQuantity}`)
        record.planQuantity = record.availableQuantity
        return
      }
      record.planQuantity = value
    },

    // 物料选择变更 (单选)
    handleMaterialChange(value, materials) {
      if (materials && materials.length > 0) {
        const material = materials[0]
        this.materialInfo = material
        this.form.setFieldsValue({
          materialCode: material.materialCode,
          materialName: material.materialName,
          specification: material.specification || '',
          color: material.color || '',
          unit: material.unit,
          unitCost: material.unitCost,
        })

        // 如果已选择仓库，自动分配库位
        const warehouseId = this.form.getFieldValue('planWarehouseId')
        const quantity = this.form.getFieldValue('planQuantity')
        if (warehouseId && value) {
          this.autoAssignLocation(value, warehouseId, quantity)
        }
      } else {
        this.materialInfo = {}
        this.form.setFieldsValue({
          materialCode: '',
          materialName: '',
          specification: '',
          color: '',
          unit: '',
          unitCost: 0,
        })
      }
    },

    // 仓库选择变更
    handleWarehouseChange(value, options) {
      if (!value || value.length === 0) {
        this.warehouseId = ''
        this.warehouseIds = [] // 清空多选ID
        this.warehouseName = ''
        return
      }

      // 如果是多选，保存所有选中的仓库ID和名称
      if (Array.isArray(value)) {
        this.warehouseIds = value

        // 仅为显示目的保存第一个仓库的ID和名称
        this.warehouseId = value[0]

        if (options && Array.isArray(options)) {
          const warehouseNames = options.map((option) => option.title || '').filter(Boolean)
          this.warehouseName = warehouseNames.join(',')
        }
      } else {
        // 兼容单选模式
        this.warehouseId = value
        this.warehouseIds = [value]
        this.warehouseName = options && options.title ? options.title : ''
      }

      // 清空库位选择
      this.form.setFieldsValue({
        planLocationId: undefined,
      })
    },

    // 批量分配库位
    batchAssignLocations() {
      if (this.selectedMaterials.length === 0) {
        this.$message.warning('请先选择物料')
        return
      }

      this.$message.loading('正在批量分配库位...')

      // 按物料类型分组
      const materialsByType = {}
      this.selectedMaterials.forEach((material) => {
        const materialType = material.materialType || '4' // 默认为其他物料类型
        if (!materialsByType[materialType]) {
          materialsByType[materialType] = []
        }
        materialsByType[materialType].push(material)
      })

      // 对每种物料类型分别处理
      const promises = []
      for (const materialType in materialsByType) {
        const materials = materialsByType[materialType]
        // 调用后端接口查询该物料类型的可用库位
        promises.push(
          getAction('/wms/location/queryAvailableLocations', {
            warehouseId: this.warehouseId,
            materialType: materialType,
          })
            .then((res) => {
              if (res.success && res.result && res.result.length > 0) {
                const availableLocations = res.result
                // 为该类型的物料分配库位
                materials.forEach((material, index) => {
                  // 如果已经有库位，则跳过
                  if (material.locationId) {
                    return
                  }

                  // 简单策略：按顺序分配库位，循环使用
                  const locationIndex = index % availableLocations.length
                  const location = availableLocations[locationIndex]

                  material.locationId = location.id
                  material.locationName = location.locationName
                })
                return materials.length
              } else {
                // 处理错误情况，可能是仓库类型与物料类型不匹配
                const errorMsg = res.message || `未找到适合物料类型${materialType}的可用库位`
                this.$message.warning(errorMsg)
                // 显示更详细的错误信息
                if (errorMsg.includes('不支持存放此类型物料')) {
                  this.$message.warning(`请确保仓库类型与物料类型匹配，或者选择其他仓库`)
                } else if (errorMsg.includes('暂不使用')) {
                  this.$message.warning(`该仓库类型${errorMsg}，请选择其他仓库`)
                }
                return 0
              }
            })
            .catch((err) => {
              console.error(`查询物料类型${materialType}的可用库位失败:`, err)
              this.$message.error(`查询物料类型${materialType}的可用库位失败`)
              return 0
            })
        )
      }

      // 等待所有物料类型的库位分配完成
      Promise.all(promises)
        .then((results) => {
          const totalAssigned = results.reduce((sum, count) => sum + count, 0)
          if (totalAssigned > 0) {
            this.$message.success(`成功为${totalAssigned}个物料分配库位`)
          } else {
            this.$message.warning('没有物料被分配库位，请检查仓库类型与物料类型是否匹配')
          }
        })
        .catch(() => {
          this.$message.error('批量分配库位失败')
        })
        .finally(() => {
          this.$message.destroy() // 关闭加载提示
        })
    },

    // 自动分配库位
    autoAssignLocation(materialId, warehouseId, quantity) {
      return new Promise((resolve, reject) => {
        this.$message.loading(`正在为物料分配库位...`)

        // 先获取物料信息，确定物料类型
        getAction('/wms/material/queryById', {
          ids: materialId,
        })
          .then((materialRes) => {
            if (materialRes.success && materialRes.result && materialRes.result.length > 0) {
              const material = materialRes.result[0]
              const materialType = material.materialType || '4' // 默认为其他物料类型

              // 根据物料类型查询对应的库位
              getAction('/wms/location/queryAvailableLocations', {
                warehouseId: warehouseId,
                materialType: materialType,
              })
                .then((res) => {
                  if (res.success && res.result && res.result.length > 0) {
                    // 找到对应类型的库位
                    const location = res.result[0]
                    this.locationName = location.locationName
                    this.form.setFieldsValue({
                      planLocationId: location.id,
                    })
                    this.$message.success(`已自动分配到库位: ${location.locationName}`)
                    resolve()
                  } else {
                    this.$message.warning('没有找到可用的库位，请手动选择')
                    resolve() // 即使没有找到库位，也视为成功，由用户手动选择
                  }
                })
                .catch((err) => {
                  console.error('查询库位信息出错:', err)
                  this.$message.error('查询库位信息出错')
                  reject(err)
                })
            } else {
              this.$message.warning('获取物料信息失败')
              reject('获取物料信息失败')
            }
          })
          .catch((err) => {
            console.error('获取物料信息出错:', err)
            this.$message.error('获取物料信息出错')
            reject(err)
          })
          .finally(() => {
            this.$message.destroy() // 关闭加载提示
          })
      })
    },

    // 入库数量变更
    handleQuantityChange(value) {
      // 如果物料ID和仓库ID都存在，重新检查库位分配
      const materialId = this.form.getFieldValue('materialId')
      const warehouseId = this.form.getFieldValue('planWarehouseId')

      if (materialId && warehouseId && value) {
        this.autoAssignLocation(materialId, warehouseId, value)
      }
    },

    // 库位选择变更
    handleLocationChange(record, value, option) {
      if (!record || !value) return

      // 更新物料的库位信息
      let index = -1

      // 根据不同模式查找索引
      if (this.isSurplusMaterial) {
        // 余料模式下，使用materialCode或者组合键作为唯一标识
        index = this.selectedMaterials.findIndex(
          (item) =>
            item.materialCode === record.materialCode ||
            (item.profileCode && item.profileCode === record.profileCode && item.surplusLength === record.surplusLength)
        )
      } else {
        // 普通模式下，使用id作为唯一标识
        index = this.selectedMaterials.findIndex((item) => item.id === record.id)
      }

      if (index > -1) {
        this.selectedMaterials[index].locationId = value

        // 尝试从option获取库位名称
        if (option && option.title) {
          this.selectedMaterials[index].locationName = option.title
        } else if (
          option &&
          option.componentOptions &&
          option.componentOptions.children &&
          option.componentOptions.children[0]
        ) {
          this.selectedMaterials[index].locationName = option.componentOptions.children[0].text
        } else {
          // 如果无法从option获取名称，尝试从其他途径获取
          getAction('/wms/location/queryById', { id: value })
            .then((res) => {
              if (res.success && res.result) {
                this.selectedMaterials[index].locationName = res.result.locationName
                // 强制更新视图
                this.$forceUpdate()
              }
            })
            .catch((err) => {
              console.error('获取库位名称失败:', err)
            })
        }

        console.log('库位已更新:', this.selectedMaterials[index].locationName, '(ID:', value, ')')
      }
    },

    // 查询采购单信息
    handleQueryPurchaseOrder() {
      const purchaseOrderNo = this.form.getFieldValue('purchaseOrderNo')
      if (!purchaseOrderNo) return

      getAction('/purchase/order/queryByOrderNo', { orderNo: purchaseOrderNo }).then((res) => {
        if (res.success && res.result) {
          // 填充采购单信息
          this.form.setFieldsValue({
            businessNo: purchaseOrderNo,
          })
        }
      })
    },

    // 加载订单编号列表
    loadProductionOrders() {
      this.orderLoading = true
      // 获取已审批通过的订单
      getAction('/oms/productSalesOrder/getOrderListWithoutYuLiaoRuku')
        .then((res) => {
          if (res.success) {
            this.productionOrders = res.result.records || []
          } else {
            this.$message.warning('获取订单编号失败: ' + res.message)
          }
          this.orderLoading = false
        })
        .catch(() => {
          this.orderLoading = false
        })
    },

    // 加载采购单列表
    loadPurchaseOrders() {
      this.purchaseOrderLoading = true
      // 获取已审核未执行完成的采购单列表
      getAction('/wms/purchase/getApprovedUncompletedList')
        .then((res) => {
          if (res.success) {
            // 将返回的采购单数据转换为下拉选择框需要的格式
            this.purchaseOrders = (res.result || []).map((order) => ({
              orderNo: order.purchaseNo,
              id: order.id,
              supplierName: order.supplier || '未知供应商',
              totalAmount: order.totalAmount,
            }))
          } else {
            this.$message.warning('获取采购单列表失败: ' + res.message)
          }
          this.purchaseOrderLoading = false
        })
        .catch((err) => {
          console.error('获取采购单列表异常:', err)
          this.$message.error('获取采购单列表异常')
          this.purchaseOrderLoading = false
        })
    },

    // 订单编号搜索处理
    handleOrderSearch(value) {
      if (value) {
        this.orderLoading = true
        // 调用后端接口进行模糊查询
        getAction('/oms/productSalesOrder/approvedList', {
          pageNo: 1,
          pageSize: 10,
          orderNo: value,
        })
          .then((res) => {
            if (res.success) {
              this.productionOrders = res.result.records || []
            } else {
              this.$message.warning('查询订单编号失败: ' + res.message)
            }
            this.orderLoading = false
          })
          .catch(() => {
            this.orderLoading = false
          })
      } else {
        this.productionOrders = []
      }
    },

    // 采购单号搜索处理
    handlePurchaseOrderSearch(value) {
      if (value) {
        this.purchaseOrderLoading = true
        // 调用后端接口进行模糊查询
        getAction('/wms/purchase/getApprovedUncompletedList')
          .then((res) => {
            if (res.success) {
              // 将返回的采购单数据转换为下拉选择框需要的格式，并根据搜索值进行过滤
              this.purchaseOrders = (res.result || [])
                .filter((order) => order.purchaseNo.includes(value))
                .map((order) => ({
                  orderNo: order.purchaseNo,
                  id: order.id,
                  supplierName: order.supplier || '未知供应商',
                  totalAmount: order.totalAmount,
                }))
            } else {
              this.$message.warning('查询采购单号失败: ' + res.message)
            }
            this.purchaseOrderLoading = false
          })
          .catch((err) => {
            console.error('查询采购单号异常:', err)
            this.$message.error('查询采购单号异常')
            this.purchaseOrderLoading = false
          })
      } else {
        // 如果搜索值为空，重新加载全部采购单
        this.loadPurchaseOrders()
      }
    },

    // 采购单号选择变更处理
    handlePurchaseOrderChange(value) {
      if (!value) {
        this.purchaseOrderId = ''
        this.inspectionIds = [] // 清空质检记录ID
        this.selectedMaterials = [] // 清空已选择的物料
        this.materialArrivalQuantity = {} // 清空已到货数量
        return
      }

      // 根据选择的采购单号获取ID
      const selectedOrder = this.purchaseOrders.find((order) => order.orderNo === value)
      if (selectedOrder) {
        // 保存采购单ID，用于后续更新执行状态
        this.purchaseOrderId = selectedOrder.id

        // 填充采购单信息
        this.form.setFieldsValue({
          businessNo: value, // 使用采购单号作为业务单号
          supplier: selectedOrder.supplierName,
        })

        // 加载已到货数量
        this.$message.loading('正在获取采购单数据...')

        // 获取物料已到货数量
        getMaterialArrivalQuantity(this.purchaseOrderId)
          .then((quantityRes) => {
            if (quantityRes.success) {
              this.materialArrivalQuantity = quantityRes.result || {}
              console.log('获取到的已到货数量数据:', this.materialArrivalQuantity)

              // 加载合格未处理的质检记录
              getQualifiedUnprocessedInspection(value)
                .then((res) => {
                  if (res.success && res.result && res.result.length > 0) {
                    // 清空已选择的物料
                    this.selectedMaterials = []
                    this.inspectionIds = []

                    // 将质检记录转换为入库单所需的物料格式
                    this.selectedMaterials = res.result.map((record) => {
                      const receivedQuantity = this.materialArrivalQuantity[record.materialId] || 0

                      // 可入库数量就是当前质检记录的合格数量
                      const availableQuantity = record.qualifiedQuantity

                      return {
                        id: record.materialId, // 设置物料ID
                        materialId: record.materialId, // 确保保存物料ID
                        materialCode: record.materialCode,
                        materialName: record.materialName,
                        materialType: record.materialType || '1', // 确保有物料类型，默认为型材(1)
                        specification: record.specification,
                        unit: record.unit,
                        originalQuantity: record.originalQuantity || 0, // 原始采购数量
                        receivedQuantity: receivedQuantity, // 已到货数量
                        availableQuantity: availableQuantity, // 可入库数量
                        planQuantity: availableQuantity > 0 ? availableQuantity : 0, // 计划入库数量 = 可入库数量
                        unitCost: record.unitCost || 0,
                        warehouseId: '', // 初始化仓库ID
                        warehouseName: '', // 初始化仓库名称
                        locationId: '', // 初始化库位ID
                        locationName: '', // 初始化库位名称
                        inspectionId: record.id, // 保存质检记录ID，用于后续更新状态
                        allInspectionIds: record.remark, // 保存所有原始质检记录ID，用于后续更新状态
                      }
                    })

                    // 过滤掉可入库数量为0的物料
                    this.selectedMaterials = this.selectedMaterials.filter((item) => item.availableQuantity > 0)

                    if (this.selectedMaterials.length === 0) {
                      this.$message.warning('该采购单没有可入库的物料（可能已全部入库或没有合格的质检记录）')
                      return
                    }

                    // 保存质检记录ID，用于入库成功后更新状态
                    // 收集所有原始质检记录ID，包括合并前的记录ID
                    this.inspectionIds = []
                    this.selectedMaterials.forEach((item) => {
                      if (item.allInspectionIds) {
                        // 如果有合并前的记录ID，添加到inspectionIds中
                        const ids = item.allInspectionIds.split(',')
                        this.inspectionIds = [...this.inspectionIds, ...ids]
                      } else if (item.inspectionId) {
                        // 如果没有合并前的记录ID，使用当前记录ID
                        this.inspectionIds.push(item.inspectionId)
                      }
                    })

                    // 设置隐藏字段materialId，用于表单验证
                    this.form.setFieldsValue({
                      materialId: this.selectedMaterials.map((item) => item.id).join(','),
                    })

                    // 尝试根据物料类型推荐库位
                    this.recommendLocationsByMaterialTypes()

                    this.$message.success(`成功加载${this.selectedMaterials.length}个可入库物料`)
                  } else {
                    this.$message.warning('该采购单没有可入库的质检合格物料')
                  }
                })
                .catch((err) => {
                  console.error('获取质检记录异常:', err)
                  this.$message.error('获取质检记录异常')
                })
                .finally(() => {
                  this.$message.destroy() // 关闭loading提示
                })
            } else {
              this.$message.error('获取已到货数量失败')
              this.$message.destroy()
            }
          })
          .catch((err) => {
            console.error('获取已到货数量异常:', err)
            this.$message.error('获取已到货数量异常')
            this.$message.destroy()
          })
      }
    },

    // 原型材类型选择变更
    handleSourceMaterialTypeChange(value) {
      this.sourceMaterialType = value
      // 清空已选择的原型材
      this.form.setFieldsValue({
        sourceMaterialId: undefined,
      })
      this.sourceMaterialInfo = {}
    },

    // 原型材选择变更
    handleSourceMaterialChange(value, materials) {
      if (!value || !materials || materials.length === 0) {
        this.sourceMaterialInfo = {}
        return
      }

      // 获取选中的原型材信息
      const material = materials[0]
      this.sourceMaterialInfo = material

      // 设置物料信息
      this.form.setFieldsValue({
        unit: material.unit,
        specification: material.specification || '', // 设置规格为原型材的规格
      })

      // 如果已输入余料长度，生成余料编号和名称
      const surplusLength = this.form.getFieldValue('surplusLength')
      if (surplusLength) {
        this.generateSurplusMaterialInfo(material, surplusLength)
      }
    },

    // 余料长度变更
    handleSurplusLengthChange(value) {
      if (!value || !this.sourceMaterialInfo.materialCode) return

      // 生成余料信息
      this.generateSurplusMaterialInfo(this.sourceMaterialInfo, value)
    },

    // 生成余料信息（编号、名称、单位成本）
    generateSurplusMaterialInfo(material, length) {
      // 生成余料编号：原型材编号+YL+余料长度
      const surplusMaterialCode = `${material.materialCode}-YL-${length}`

      // 生成余料名称：原型材名称+YL+余料长度
      const surplusMaterialName = `${material.materialName}-YL-${length}`

      // 计算单位成本：原型材成本/原型材长度*余料长度
      let unitCost = 0
      if (material.unitCost && material.length && material.length > 0) {
        unitCost = (material.unitCost / material.length) * length
      }

      // 设置表单值
      this.form.setFieldsValue({
        materialCode: surplusMaterialCode, // 设置生成的余料编码
        materialName: surplusMaterialName,
        unitCost: unitCost.toFixed(2),
      })
    },

    // 获取业务类型名称
    getBusinessTypeName() {
      const businessType = this.businessType
      switch (businessType) {
        case '11':
          return '采购入库'
        case '12':
          return '余料入库'
        case '13':
          return '调拨入库'
        case '19':
          return '其他入库'
        default:
          return ''
      }
    },

    // 获取生产订单编号
    getProductionOrderNo() {
      const productionOrderId = this.form.getFieldValue('productionOrderId')
      if (!productionOrderId) return ''

      // 从已加载的订单列表中查找对应的订单编号
      const order = this.productionOrders.find((o) => o.id === productionOrderId)
      return order ? order.orderNo : ''
    },

    // 加载仓库名称缓存
    loadWarehouseNames() {
      // 获取所有仓库信息
      return new Promise((resolve, reject) => {
        getAction('/wms/warehouse/listAll')
          .then((res) => {
            if (res.success && res.result) {
              const warehouseList = res.result
              this.warehouseList = warehouseList // 保存仓库列表

              const warehouseMap = {}
              warehouseList.forEach((warehouse) => {
                warehouseMap[warehouse.id] = warehouse.warehouseName
              })

              // 更新仓库名称缓存
              this.warehouseNameMap = warehouseMap

              // 更新已选物料的仓库名称
              this.updateMaterialsWarehouseName()

              console.log('已加载仓库数据:', warehouseList.length, '个仓库')
              resolve(warehouseList)
            } else {
              console.error('加载仓库数据失败:', res.message || '未知错误')
              this.$message.error('加载仓库数据失败，请刷新页面重试')
              reject(new Error(res.message || '加载仓库数据失败'))
            }
          })
          .catch((err) => {
            console.error('加载仓库数据异常:', err)
            this.$message.error('加载仓库数据异常，请刷新页面重试')
            reject(err)
          })
      })
    },

    // 更新物料的仓库名称
    updateMaterialsWarehouseName() {
      if (!this.selectedMaterials || this.selectedMaterials.length === 0) return

      let updated = false

      this.selectedMaterials.forEach((material) => {
        if (material.warehouseId) {
          // 从缓存中获取仓库名称
          const warehouseName = this.warehouseNameMap[material.warehouseId]
          if (warehouseName) {
            material.warehouseName = warehouseName
            updated = true
          } else {
            // 如果缓存中没有，尝试从仓库列表中查找
            const warehouse = this.warehouseList.find((w) => w.id === material.warehouseId)
            if (warehouse) {
              material.warehouseName = warehouse.warehouseName
              // 更新缓存
              this.warehouseNameMap[material.warehouseId] = warehouse.warehouseName
              updated = true
            } else {
              console.warn(`未找到仓库ID为${material.warehouseId}的仓库名称`)
            }
          }
        }
      })

      // 如果有更新，强制刷新视图
      if (updated) {
        this.$nextTick(() => {
          this.$forceUpdate()
        })
      }
    },

    // 根据物料类型推荐仓库
    recommendWarehouseByMaterialType() {
      if (this.selectedMaterials.length === 0) {
        this.$message.warning('请先选择物料')
        return
      }

      // 确保已加载仓库数据
      if (this.warehouseList.length === 0) {
        this.$message.info('正在加载仓库数据...')
        this.loadWarehouseNames()
      }

      this.$message.loading('正在根据物料类型推荐库位...')

      // 准备请求参数
      const params = {
        materials: this.selectedMaterials.map((material) => ({
          id: material.id,
          materialCode: material.materialCode,
          materialType: material.materialType || '4', // 默认为其他物料类型
        })),
      }

      // 调用后端接口查询可用库位
      postAction('/wms/location/recommendLocationsByMaterialTypes', params)
        .then((res) => {
          if (res.success && res.result) {
            const results = res.result
            let successCount = 0
            let errorMessages = []

            // 处理每个物料的分配结果
            results.forEach((result) => {
              const materialId = result.materialId
              const materialCode = result.materialCode

              // 查找对应的物料
              const materialIndex = this.selectedMaterials.findIndex(
                (m) => m.id === materialId || m.materialCode === materialCode
              )

              if (materialIndex === -1) return

              // 如果返回了所有仓库列表，更新全局仓库列表
              if (result.allWarehouses && result.allWarehouses.length > 0) {
                this.warehouseList = result.allWarehouses

                // 更新仓库名称映射
                const warehouseMap = {}
                result.allWarehouses.forEach((warehouse) => {
                  warehouseMap[warehouse.id] = warehouse.warehouseName
                })
                this.warehouseNameMap = { ...this.warehouseNameMap, ...warehouseMap }

                console.log('已更新仓库列表:', this.warehouseList.length, '个仓库')
              }

              if (result.success) {
                // 成功分配库位
                this.selectedMaterials[materialIndex].warehouseId = result.warehouseId
                this.selectedMaterials[materialIndex].warehouseName = result.warehouseName
                this.selectedMaterials[materialIndex].warehouseType = result.warehouseType
                this.selectedMaterials[materialIndex].locationId = result.locationId
                this.selectedMaterials[materialIndex].locationName = result.locationName

                // 保存可用库位列表，方便用户选择
                if (result.availableLocations && result.availableLocations.length > 0) {
                  this.selectedMaterials[materialIndex].availableLocations = result.availableLocations
                }

                successCount++

                console.log(`成功为物料[${materialCode}]分配库位: ${result.locationName} (${result.locationId})`)
              } else {
                // 分配失败，记录错误信息
                const materialCode = this.selectedMaterials[materialIndex].materialCode
                errorMessages.push(`物料[${materialCode}]: ${result.error}`)
              }
            })

            // 显示结果
            if (successCount > 0) {
              this.$message.success(`成功为${successCount}个物料分配库位`)
              this.$message.info('您可以在表格中手动修改分配的仓库和库位')

              // 更新仓库名称映射
              results.forEach((result) => {
                if (result.success && result.warehouseId && result.warehouseName) {
                  this.warehouseNameMap[result.warehouseId] = result.warehouseName
                }
              })

              // 更新物料的仓库名称
              this.updateMaterialsWarehouseName()

              // 强制更新视图
              this.$nextTick(() => {
                this.$forceUpdate()
              })
            }

            if (errorMessages.length > 0) {
              // 显示错误信息
              this.$message.warning(`${errorMessages.length}个物料分配库位失败`)

              // 如果错误信息较多，使用模态框显示详细信息
              if (errorMessages.length > 3) {
                this.$confirm({
                  title: '库位分配失败详情',
                  content: errorMessages.join('<br/>'),
                  width: 500,
                })
              } else {
                // 少量错误直接显示
                errorMessages.forEach((msg) => {
                  this.$message.warning(msg)
                })
              }
            }
          } else {
            this.$message.error(res.message || '推荐库位失败')
          }
        })
        .catch((err) => {
          console.error('推荐库位失败:', err)
          this.$message.error('推荐库位失败')
        })
        .finally(() => {
          this.$message.destroy() // 关闭加载提示
        })
    },

    // 获取仓库名称
    getWarehouseName(warehouseId) {
      if (!warehouseId) return ''

      // 如果仓库名称缓存已存在，直接使用
      if (this.warehouseNameMap && this.warehouseNameMap[warehouseId]) {
        return this.warehouseNameMap[warehouseId]
      }

      // 否则返回空字符串，等待异步加载
      return ''
    },

    // 处理物料表格中的仓库选择变更
    handleWarehouseChangeForMaterial(record, value, option) {
      if (!record || !value) return

      // 更新物料的仓库信息
      const index = this.selectedMaterials.findIndex((item) => item.id === record.id)
      if (index > -1) {
        this.selectedMaterials[index].warehouseId = value

        // 获取仓库名称
        if (
          option &&
          option.componentOptions &&
          option.componentOptions.children &&
          option.componentOptions.children[0]
        ) {
          this.selectedMaterials[index].warehouseName = option.componentOptions.children[0].text
        } else {
          // 如果无法从option获取名称，则从仓库缓存中获取
          const warehouse = this.warehouseList.find((w) => w.id === value)
          if (warehouse) {
            this.selectedMaterials[index].warehouseName = warehouse.warehouseName
            // 更新缓存
            this.warehouseNameMap[value] = warehouse.warehouseName
          } else {
            this.selectedMaterials[index].warehouseName = this.warehouseNameMap[value] || ''
          }
        }

        // 清空库位选择
        this.selectedMaterials[index].locationId = undefined
        this.selectedMaterials[index].locationName = ''

        // 自动查询该仓库下的可用库位
        this.queryAvailableLocationsForMaterial(this.selectedMaterials[index])

        console.log('仓库已更新:', this.selectedMaterials[index].warehouseName, '(ID:', value, ')')

        // 强制更新视图
        this.$forceUpdate()
      }
    },

    // 查询物料在指定仓库的可用库位
    queryAvailableLocationsForMaterial(material) {
      if (!material || !material.warehouseId) return

      this.$message.loading(`正在查询仓库可用库位...`)

      // 检查仓库类型与物料类型是否匹配
      const selectedWarehouse = this.warehouseList.find((w) => w.id === material.warehouseId)
      const materialType = material.materialType || '4' // 默认为其他物料类型
      let isMatched = false

      if (selectedWarehouse && materialType) {
        isMatched = selectedWarehouse.warehouseType === materialType
      }

      // 如果类型不匹配，显示警告
      if (!isMatched && selectedWarehouse) {
        console.log(`警告：仓库类型(${selectedWarehouse.warehouseType})与物料类型(${materialType})不匹配`)
      }

      // 调用后端接口查询可用库位
      getAction('/wms/location/queryAvailableLocations', {
        warehouseId: material.warehouseId,
        materialType: materialType,
      })
        .then((res) => {
          if (res.success && res.result && res.result.length > 0) {
            // 保存可用库位列表
            material.availableLocations = res.result.map((location) => ({
              id: location.id,
              locationName: location.locationName,
              locationCode: location.locationCode,
              status: location.status,
            }))

            // 自动选择第一个可用库位
            const firstLocation = res.result[0]
            material.locationId = firstLocation.id
            material.locationName = firstLocation.locationName

            this.$message.success(`已找到${res.result.length}个可用库位`)
          } else {
            this.$message.warning('没有找到可用的库位，请手动选择')
            resolve() // 即使没有找到库位，也视为成功，由用户手动选择
          }
        })
        .catch((err) => {
          console.error('查询库位信息出错:', err)
          this.$message.error('查询库位信息出错')
          reject(err)
        })
    },

    // 源仓库选择变更处理
    handleSourceWarehouseChange(value, option) {
      if (!value) {
        this.sourceWarehouseId = ''
        this.sourceWarehouseName = ''
        this.sourceInventoryList = []
        return
      }

      // 获取仓库名称
      let warehouseName = ''
      if (option && option.title) {
        warehouseName = option.title
      } else if (
        option &&
        option.componentOptions &&
        option.componentOptions.children &&
        option.componentOptions.children[0]
      ) {
        warehouseName = option.componentOptions.children[0].text
      } else {
        // 尝试从仓库列表中获取名称
        const warehouse = this.warehouseList.find((w) => w.id === value)
        if (warehouse) {
          warehouseName = warehouse.warehouseName
        }
      }

      this.sourceWarehouseId = value
      this.sourceWarehouseName = warehouseName

      console.log('选择源仓库:', warehouseName, '(ID:', value, ')')

      // 清空已选择的库存记录
      this.sourceInventoryList = []
      this.selectedInventoryKeys = []
      this.selectedInventoryRows = []
    },

    // 查询源仓库库存
    querySourceInventory() {
      if (!this.sourceWarehouseId) {
        this.$message.warning('请先选择源仓库')
        return
      }

      this.sourceInventoryLoading = true
      this.selectedInventoryKeys = []
      this.selectedInventoryRows = []

      // 调用接口查询源仓库库存
      getAction('/wms/inventory/list', { warehouseId: this.sourceWarehouseId, pageSize: 500 })
        .then((res) => {
          if (res.success) {
            // 处理库存数据
            const inventoryList = res.result.records || []

            // 过滤出可用库存大于0的记录
            this.sourceInventoryList = inventoryList
              .filter((item) => item.availableQuantity > 0)
              .map((item) => ({
                ...item,
                transferQuantity: 1, // 默认调拨数量为1
                targetWarehouseId: undefined, // 目标仓库ID
                targetWarehouseName: '', // 目标仓库名称
                targetLocationId: undefined, // 目标库位ID
                targetLocationName: '', // 目标库位名称
                sourceWarehouseId: this.sourceWarehouseId, // 源仓库ID
                sourceWarehouseName: this.sourceWarehouseName, // 源仓库名称
                sourceLocationId: item.locationId, // 源库位ID
                sourceLocationName: item.locationName, // 源库位名称
              }))

            if (this.sourceInventoryList.length === 0) {
              this.$message.warning('该仓库没有可调拨的库存')
            } else {
              this.$message.success(`成功查询到${this.sourceInventoryList.length}条可调拨库存记录`)
            }
          } else {
            this.$message.error(res.message || '查询库存失败')
          }
        })
        .catch((err) => {
          console.error('查询库存异常:', err)
          this.$message.error('查询库存异常')
        })
        .finally(() => {
          this.sourceInventoryLoading = false
        })
    },

    // 选择库存记录变更
    onSelectInventoryChange(selectedRowKeys, selectedRows) {
      this.selectedInventoryKeys = selectedRowKeys
      this.selectedInventoryRows = selectedRows

      console.log('已选择库存记录:', selectedRows.length)
    },

    // 目标仓库选择变更
    handleTargetWarehouseChange(record, value, option) {
      if (!record || !value) return

      // 获取仓库名称
      let warehouseName = ''
      if (option && option.title) {
        warehouseName = option.title
      } else if (
        option &&
        option.componentOptions &&
        option.componentOptions.children &&
        option.componentOptions.children[0]
      ) {
        warehouseName = option.componentOptions.children[0].text
      } else {
        // 尝试从仓库列表中获取名称
        const warehouse = this.warehouseList.find((w) => w.id === value)
        if (warehouse) {
          warehouseName = warehouse.warehouseName
        }
      }

      // 更新记录的目标仓库信息
      const index = this.sourceInventoryList.findIndex((item) => item.id === record.id)
      if (index > -1) {
        this.sourceInventoryList[index].targetWarehouseId = value
        this.sourceInventoryList[index].targetWarehouseName = warehouseName

        // 清空目标库位
        this.sourceInventoryList[index].targetLocationId = undefined
        this.sourceInventoryList[index].targetLocationName = ''

        // 强制更新视图
        this.$forceUpdate()

        // 获取目标仓库中可用的库位（状态为1空闲或2占用且物料编码相同的库位）
        this.loadAvailableLocationsForTargetWarehouse(record, value)
      }
    },

    // 加载目标仓库可用库位
    loadAvailableLocationsForTargetWarehouse(record, warehouseId) {
      if (!warehouseId || !record || !record.materialCode) return

      // 显示加载中提示
      this.$message.loading('正在加载可用库位...')

      // 调用接口获取目标仓库中可用的库位
      getAction('/wms/location/queryAvailableLocationsForTransfer', {
        warehouseId: warehouseId,
        materialCode: record.materialCode,
      })
        .then((res) => {
          if (res.success) {
            // 更新记录的可用库位列表
            const index = this.sourceInventoryList.findIndex((item) => item.id === record.id)
            if (index > -1) {
              this.sourceInventoryList[index].availableLocations = res.result || []

              // 如果有可用库位，默认选择第一个
              if (this.sourceInventoryList[index].availableLocations.length > 0) {
                const firstLocation = this.sourceInventoryList[index].availableLocations[0]
                this.sourceInventoryList[index].targetLocationId = firstLocation.id
                this.sourceInventoryList[index].targetLocationName = firstLocation.locationName

                this.$message.success(`已找到${this.sourceInventoryList[index].availableLocations.length}个可用库位`)
              } else {
                this.$message.warning('没有找到可用的库位')
              }

              // 强制更新视图
              this.$forceUpdate()
            }
          } else {
            this.$message.error(res.message || '获取可用库位失败')
          }
        })
        .catch((err) => {
          console.error('获取可用库位异常:', err)
          this.$message.error('获取可用库位异常')
        })
        .finally(() => {
          this.$message.destroy() // 关闭加载提示
        })
    },

    // 目标库位选择变更
    handleTargetLocationChange(record, value, option) {
      if (!record || !value) return

      // 获取库位名称
      let locationName = ''
      if (option && option.title) {
        locationName = option.title
      } else if (
        option &&
        option.componentOptions &&
        option.componentOptions.children &&
        option.componentOptions.children[0]
      ) {
        locationName = option.componentOptions.children[0].text
      }

      // 更新记录的目标库位信息
      const index = this.sourceInventoryList.findIndex((item) => item.id === record.id)
      if (index > -1) {
        this.sourceInventoryList[index].targetLocationId = value
        this.sourceInventoryList[index].targetLocationName = locationName

        // 如果没有库位名称，尝试从API获取
        if (!locationName) {
          getAction('/wms/location/queryById', { id: value })
            .then((res) => {
              if (res.success && res.result) {
                this.sourceInventoryList[index].targetLocationName = res.result.locationName
                // 强制更新视图
                this.$forceUpdate()
              }
            })
            .catch((err) => {
              console.error('获取库位名称失败:', err)
            })
        }

        // 强制更新视图
        this.$forceUpdate()
      }
    },

    // 添加到调拨物料列表
    addToTransferList() {
      if (this.selectedInventoryKeys.length === 0) {
        this.$message.warning('请选择要调拨的库存')
        return
      }

      // 验证选中的记录是否都填写了调拨数量和目标库位
      const invalidRecords = this.selectedInventoryRows.filter(
        (item) =>
          !item.transferQuantity ||
          item.transferQuantity <= 0 ||
          item.transferQuantity > item.availableQuantity ||
          !item.targetWarehouseId ||
          !item.targetLocationId
      )

      if (invalidRecords.length > 0) {
        this.$message.warning('请确保所有选中的记录都填写了有效的调拨数量和目标库位')
        return
      }

      // 将选中的库存记录转换为调拨物料
      const transferMaterials = this.selectedInventoryRows.map((item) => ({
        id: item.id, // 使用库存记录ID作为唯一标识
        materialId: item.materialId,
        materialCode: item.materialCode,
        materialName: item.materialName,
        materialType: item.materialType,
        specification: item.specification,
        unit: item.unit,
        planQuantity: item.transferQuantity, // 使用调拨数量作为计划入库数量
        unitCost: item.unitCost || 0, // 保留单位成本
        warehouseId: item.targetWarehouseId, // 目标仓库ID
        warehouseName: item.targetWarehouseName, // 目标仓库名称
        locationId: item.targetLocationId, // 目标库位ID
        locationName: item.targetLocationName, // 目标库位名称
        sourceWarehouseId: item.sourceWarehouseId, // 源仓库ID
        sourceWarehouseName: item.sourceWarehouseName, // 源仓库名称
        sourceLocationId: item.locationId, // 源库位ID
        sourceLocationName: item.locationName, // 源库位名称
        batchNo: item.batchNo, // 批次号
        originalDetailId: item.id, // 原始库存记录ID
        totalCost: (item.transferQuantity * (item.unitCost || 0)).toFixed(2), // 总成本
      }))

      // 检查是否有重复的物料（相同物料、源仓库、源库位、目标仓库、目标库位）
      const newMaterials = []

      transferMaterials.forEach((newItem) => {
        const existingIndex = this.selectedMaterials.findIndex(
          (existItem) =>
            existItem.materialId === newItem.materialId &&
            existItem.sourceWarehouseId === newItem.sourceWarehouseId &&
            existItem.sourceLocationId === newItem.sourceLocationId &&
            existItem.warehouseId === newItem.warehouseId &&
            existItem.locationId === newItem.locationId
        )

        if (existingIndex > -1) {
          // 如果已存在，合并数量
          this.selectedMaterials[existingIndex].planQuantity += newItem.planQuantity
          this.selectedMaterials[existingIndex].totalCost = (
            this.selectedMaterials[existingIndex].planQuantity * this.selectedMaterials[existingIndex].unitCost
          ).toFixed(2)
        } else {
          // 否则添加新记录
          newMaterials.push(newItem)
        }
      })

      // 添加新记录到已选物料列表
      this.selectedMaterials = [...this.selectedMaterials, ...newMaterials]

      // 清空选择
      this.selectedInventoryKeys = []
      this.selectedInventoryRows = []

      this.$message.success(`已添加${transferMaterials.length}个物料到调拨列表`)

      // 设置隐藏字段materialId，用于表单验证
      if (this.selectedMaterials.length > 0) {
        const materialIds = this.selectedMaterials.map((item) => item.materialId).join(',')
        this.form.setFieldsValue({
          materialId: materialIds,
        })
      }
    },

    // 移除调拨物料
    removeTransferMaterial(record) {
      const index = this.selectedMaterials.findIndex((item) => item.id === record.id)
      if (index > -1) {
        this.selectedMaterials.splice(index, 1)

        // 更新表单中的materialId值
        if (this.selectedMaterials.length > 0) {
          const materialIds = this.selectedMaterials.map((item) => item.materialId).join(',')
          this.form.setFieldsValue({
            materialId: materialIds,
          })
        } else {
          this.form.setFieldsValue({
            materialId: undefined,
          })
        }

        this.$message.success('已移除该物料')
      }
    },

    // 根据物料类型推荐库位（调用后端接口）
    recommendLocationsByMaterialTypes() {
      if (this.selectedMaterials.length === 0) {
        this.$message.warning('请先选择物料')
        return
      }

      this.$message.loading('正在根据物料类型推荐库位...')

      // 准备请求参数
      const params = {
        materials: this.selectedMaterials.map((material) => ({
          id: material.id,
          materialCode: material.materialCode,
          materialType: material.materialType || '4', // 默认为其他物料类型
        })),
      }

      // 调用后端接口查询可用库位
      postAction('/wms/location/recommendLocationsByMaterialTypes', params)
        .then((res) => {
          if (res.success && res.result) {
            const results = res.result
            let successCount = 0
            let errorMessages = []

            // 处理每个物料的分配结果
            results.forEach((result) => {
              const materialId = result.materialId
              const materialCode = result.materialCode

              // 查找对应的物料
              const materialIndex = this.selectedMaterials.findIndex(
                (m) => m.id === materialId || m.materialCode === materialCode
              )

              if (materialIndex === -1) return

              // 如果返回了所有仓库列表，更新全局仓库列表
              if (result.allWarehouses && result.allWarehouses.length > 0) {
                this.warehouseList = result.allWarehouses

                // 更新仓库名称映射
                const warehouseMap = {}
                result.allWarehouses.forEach((warehouse) => {
                  warehouseMap[warehouse.id] = warehouse.warehouseName
                })
                this.warehouseNameMap = { ...this.warehouseNameMap, ...warehouseMap }

                console.log('已更新仓库列表:', this.warehouseList.length, '个仓库')
              }

              if (result.success) {
                // 成功分配库位
                this.selectedMaterials[materialIndex].warehouseId = result.warehouseId
                this.selectedMaterials[materialIndex].warehouseName = result.warehouseName
                this.selectedMaterials[materialIndex].warehouseType = result.warehouseType
                this.selectedMaterials[materialIndex].locationId = result.locationId
                this.selectedMaterials[materialIndex].locationName = result.locationName

                // 保存可用库位列表，方便用户选择
                if (result.availableLocations && result.availableLocations.length > 0) {
                  this.selectedMaterials[materialIndex].availableLocations = result.availableLocations
                }

                successCount++

                console.log(`成功为物料[${materialCode}]分配库位: ${result.locationName} (${result.locationId})`)
              } else {
                // 分配失败，记录错误信息
                const materialCode = this.selectedMaterials[materialIndex].materialCode
                errorMessages.push(`物料[${materialCode}]: ${result.error}`)
              }
            })

            // 显示结果
            if (successCount > 0) {
              this.$message.success(`成功为${successCount}个物料分配库位`)
              this.$message.info('您可以在表格中手动修改分配的仓库和库位')

              // 更新仓库名称映射
              results.forEach((result) => {
                if (result.success && result.warehouseId && result.warehouseName) {
                  this.warehouseNameMap[result.warehouseId] = result.warehouseName
                }
              })

              // 更新物料的仓库名称
              this.updateMaterialsWarehouseName()

              // 强制更新视图
              this.$nextTick(() => {
                this.$forceUpdate()
              })
            }

            if (errorMessages.length > 0) {
              // 显示错误信息
              this.$message.warning(`${errorMessages.length}个物料分配库位失败`)

              // 如果错误信息较多，使用模态框显示详细信息
              if (errorMessages.length > 3) {
                this.$confirm({
                  title: '库位分配失败详情',
                  content: errorMessages.join('<br/>'),
                  width: 500,
                })
              } else {
                // 少量错误直接显示
                errorMessages.forEach((msg) => {
                  this.$message.warning(msg)
                })
              }
            }
          } else {
            this.$message.error(res.message || '推荐库位失败')
          }
        })
        .catch((err) => {
          console.error('推荐库位失败:', err)
          this.$message.error('推荐库位失败')
        })
        .finally(() => {
          this.$message.destroy() // 关闭加载提示
        })
    },
  },
}
</script>
